package com.sgolub.commanndsonline.dao.entity;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sgolub.commanndsonline.dao.sec.SecUserDAO;
import com.sgolub.commanndsonline.domain.entity.AdvertisingRegistry;
import com.sgolub.commanndsonline.domain.entity.UserBasket;
import com.sgolub.commanndsonline.domain.entity.UserOrder;
import com.sgolub.commanndsonline.domain.entity.UserOrderDetail;
import com.sgolub.commanndsonline.domain.sec.SecUser;
import com.sgolub.commanndsonline.ws.entity.AdvertisingRegistryOperation;

/**
 * @author sgolub
 *
 */
@Repository
public class UserBasketDAOImpl implements UserBasketDAO {

    @Autowired
    private SessionFactory sessionFactory;
    
    @Autowired
    private UserOrderDAO orderDAO;
    
    @Autowired
    private UserOrderDetailDAO orderDetailDAO;   
     
    @Autowired
    private SecUserDAO secUserDAO;
    
	public UserBasket get(Integer id) {
		UserBasket userBasket = (UserBasket)sessionFactory.
								getCurrentSession().get(UserBasket.class, id);
		return userBasket;
	}

	
	public String	checkOneItem (Integer 		id){
		return "OK";
	}
	
	public void add(UserBasket userBasket) {
		sessionFactory.getCurrentSession().save(userBasket);

	}

	public void update(UserBasket userBasket) {
		sessionFactory.getCurrentSession().update(userBasket);
	} 

	public void remove(Integer id) {
		sessionFactory.getCurrentSession().delete(get(id));
	}

	@SuppressWarnings("unchecked")
	public List<UserBasket> list() {
		return sessionFactory.getCurrentSession().createQuery("from UserBasket").list();
	}

	@SuppressWarnings("unchecked")
	public List<UserBasket> filter() {
		return sessionFactory.getCurrentSession().createQuery("from UserBasket").list();
	}

	@SuppressWarnings("unchecked")
	public List<UserBasket> listCurrentUserBasket(Integer userId){
		
		String sql = "from UserBasket where fk_sec_user_id = " + userId + " order by fk_advertising_registry_id";
		Query queryH = sessionFactory.getCurrentSession().createQuery(sql);
		List<UserBasket> userBasketList = queryH.list();	
		return userBasketList;
	}
	
	@SuppressWarnings("unchecked")
	public List<UserBasket> advansedListCurrentWithPaginationJQGrid
	(Integer userId, int rowsPerPage, int currentPage, String sortByColumn, String sortMode){
    	System.out.println("== UserBasketDAOImpl.advansedListCurrentWithPaginationJQGrid ==");
    	System.out.println("== PASSED FILTERS ==");
    	String sql = "from UserBasket where fk_sec_user_id = " + userId;
    	
    	if (sortByColumn.length()>0 & sortMode.length()>0){
    		sql = sql + " order by " + sortByColumn + " " + sortMode;
		}
    	
    	Query queryH = sessionFactory.getCurrentSession().createQuery(sql);
		List<UserBasket> userBasketList = queryH.list();	
		return userBasketList;
	}
	
	public String clearCurrentUserBasket(Integer userId){
		List<UserBasket> userBasketList = listCurrentUserBasket(userId);
		Iterator <UserBasket> userBasketIterator = userBasketList.iterator();
		while(userBasketIterator.hasNext()) {
			UserBasket elementSrc = userBasketIterator.next();
			remove(elementSrc.getId());
		}
		return "OK-200"; 
	}
	
	public String addItemToCurrentUserBasket(Integer userId, Integer itemId, Date beginCommandDate){
		UserBasket basketItem = new UserBasket();
		AdvertisingRegistry registryItem = 
				(AdvertisingRegistry)sessionFactory
					.getCurrentSession().load(AdvertisingRegistry.class, itemId);
		
		SecUser userItem = (SecUser)sessionFactory.getCurrentSession().load(SecUser.class, userId);
		
		basketItem.setSecUser(userItem);
		basketItem.setAdvertisingRegistry(registryItem);
		basketItem.setBeginCommandDate(beginCommandDate);
		basketItem.setReservationType(0);
		
		sessionFactory.getCurrentSession().save(basketItem);
		
		return "OK-200";
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public String submitCurrentUserBasket(Integer userId){
		String sql = "from UserBasket where fk_sec_user_id = " + userId + " order by fk_advertising_registry_id";
		Query queryH = sessionFactory.getCurrentSession().createQuery(sql);
		List<UserBasket> userBasketList = queryH.list();
		
		if (userBasketList.size()<1) return "ERROR";
		
		Date curDate = new Date();
		
		String newOrderNr = curDate.getYear() + 
				"/" + curDate.getHours() + curDate.getMinutes() + curDate.getSeconds();
		Integer newOrderId;
		//Create Order Item
		UserOrder order = new UserOrder();
		order.setOrderNr(newOrderNr);
		
		SecUser currUser = new SecUser();
		currUser = secUserDAO.get(userId);
		
		SecUser currUserManager = new SecUser();
		currUserManager = currUser.getManager();
		
		order.setSecUser(currUser);
		order.setManager(currUserManager);
		
		order.setOrderStatus(0);
		order.setOrderDate(new Date());
		orderDAO.add(order);
		newOrderId = order.getId();
		
		Iterator<UserBasket> userBasketIterator = userBasketList.iterator();
		 while(userBasketIterator.hasNext()) {
			 UserBasket itemBasket = userBasketIterator.next();
			 UserOrderDetail itemOrderDetail = new UserOrderDetail();
			 
			 itemOrderDetail.setAdvertisingRegistry(itemBasket.getAdvertisingRegistry());
			 itemOrderDetail.setFkOrderId(newOrderId);
			 itemOrderDetail.setBeginCommandDate(itemBasket.getBeginCommandDate());
			 itemOrderDetail.setEndCommandDate(itemBasket.getEndCommandDate());
			 itemOrderDetail.setReservationType(itemBasket.getReservationType());
			 
			 orderDetailDAO.add(itemOrderDetail);
			 
			 sessionFactory.getCurrentSession().delete(itemBasket);
		 }
		
		return newOrderNr;
	}
}
